#!/usr/bin/python3.6
# encoding:utf-8
import datetime
import os, sys
import time
import logging

# 创建日志器对象
logger = logging.getLogger(__name__)

# 设置logger可输出日志级别范围
logger.setLevel(logging.DEBUG)

# 添加控制台handler，用于输出日志到控制台
console_handler = logging.StreamHandler()
# 添加日志文件handler，用于输出日志到文件中
logfile = "D:/XRobot40Log/runing."+datetime.datetime.now().strftime ("%Y%m%d")+".log"
file_handler = logging.FileHandler(filename=logfile, encoding='UTF-8')

# 将handler添加到日志器中
logger.addHandler(console_handler)
logger.addHandler(file_handler)

# 设置格式并赋予handler
formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
console_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)


def arraytolog(a, k='M'):
    rlt = ""
    if type(a) == list:
        for stem in a:
            if k == "S":
                rlt = rlt + "%3s" % stem
            elif k == "M":
                rlt = rlt + "%5s" % stem
            elif k == "L":
                rlt = rlt + "%8s" % stem
            else:
                rlt = rlt + "%15s" % stem
    else:
        print("* The input is not a list")
    return rlt


def logoutold(loginfo="no info", logfile=logfile, loglevel="Info", logflag="------", is_print=1):
    dt = str(datetime.datetime.now())[0:19]
    line = "%s - %-7s - %-10s %s\n" % (dt, loglevel, logflag, loginfo)
    if is_print != 0:
        print(loginfo)

    loghourfile = logfile + "." + dt[0:13].replace(" ", ".").replace("-", "")
    # print(loghourfile)
    try:
        if os.path.exists(loghourfile) == False:
            f = open(loghourfile, 'w')
            f.close
        with open(loghourfile, "a") as f:
            f.write(line)
    except:
        loghourfile = loghourfile + "." + str(time.time())
        if os.path.exists(loghourfile) == False:
            f = open(loghourfile, 'w')
            f.close
        with open(loghourfile, "a") as f:
            f.write(line)


def logout(loginfo="no info", loglevel="debug"):
    if loglevel == "debug":
        logger.debug(loginfo)
    if loglevel == "info":
        logger.info(loginfo)
    if loglevel == "warning":
        logger.warning(loginfo)
    if loglevel == "critical":
        logger.critical(loginfo)
    if loglevel == "error":
        logger.error(loginfo)


if __name__ == '__main__':
    logout(loginfo="this line is a log!!!")

    # print(arraytolog([1,2,3]))